//
//  RootViewController.m
//  WonderfulNotes
//
//  Created by 千锋 on 16/1/6.
//  Copyright © 2016年 andy. All rights reserved.
//

#import "RootViewController.h"
#import "LeftMenuViewController.h"
#import "SearchViewController.h"
#import "WriteViewController.h"
#import <RESideMenu.h>
#import "AppDelegate.h"
#import "AllUtils.h"
#import "NoteCell.h"
#import "AppDelegate.h"
#import "NoteModel.h"
#import "BmobOperation.h"

@interface RootViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    BOOL isEditing;
}
@property (nonatomic,strong) UIView * noteView;
@property (nonatomic,strong) UITableView * tableView;
@property (nonatomic,strong) NSMutableArray * dataArray;
@property (nonatomic,strong) NSMutableArray * editArray;

@end

@implementation RootViewController

-(NSMutableArray *)editArray{
    
    if (_editArray==nil) {
        _editArray =@[].mutableCopy;
    }
    return _editArray;
}

//只会运行一次
- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.9];
    [self createView];
    [self createNaviBarItem];
    [self queryNoteId:@"Note" limitCount:50];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryNoteId:limitCount:) name:UPLOAD_NOTICE object:nil];
    
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:UPLOAD_NOTICE];
}


-(void)createNaviBarItem{
    
    UILabel * titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    titleLab.text = @"☁️笔记";
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLab;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"tabbar_coppose_left"] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonItemClick)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"tabbar_discover"] style:UIBarButtonItemStyleDone target:self action:@selector(rightBarButtonItemClick)];
    
    UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-25, SCREEN_HEIGHT-60, 50, 50)];
    button.layer.cornerRadius = 25;
    button.layer.borderColor = [UIColor whiteColor].CGColor;
    button.layer.borderWidth = 2;
    button.backgroundColor = [UIColor cyanColor];
    [button addTarget:self action:@selector(middleButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];

}

-(void)createView{
    
    self.noteView = [[UIView alloc]initWithFrame:CGRectMake(0, 65, SCREEN_WIDTH, 50)];
    self.noteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.noteView];
    
    UIImageView * IconImage = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 40, 40)];
    IconImage.image = [UIImage imageNamed:@"tableview_note"];
    [self.noteView addSubview:IconImage];
    
    UILabel * noteLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(IconImage.frame)+10, CGRectGetMinY(IconImage.frame), 80, 40)];
    noteLabel.text = @"☁️笔记";
    noteLabel.textColor = [UIColor grayColor];
    noteLabel.font = [UIFont systemFontOfSize:18];
    [self.noteView addSubview:noteLabel];
    
    UIImageView * lastView = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.view.frame)-50, CGRectGetMinY(IconImage.frame), 45, 45)];
    lastView.image = [UIImage imageNamed:@"tableview_arrow"];
    [self.noteView addSubview:lastView];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.noteView.frame), SCREEN_WIDTH, 5*50)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"NoteCell" bundle:nil] forCellReuseIdentifier:@"NoteCell"];
    
}

-(void)queryNoteId:(NSString *)tableName limitCount:(int)limitCount {
    
    
    self.dataArray = [NSMutableArray array];
    [SVProgressHUD showWithStatus:@"加载中..." maskType:SVProgressHUDMaskTypeClear];
    BmobQuery * bquery = [BmobQuery queryWithClassName:@"Note"];
    bquery.limit =limitCount;
    //先从缓存读取数据，如果没有再从网络获取。
    bquery.cachePolicy = kBmobCachePolicyNetworkElseCache;
    [bquery orderByDescending:@"updatedAt"];
    [bquery findObjectsInBackgroundWithBlock:^(NSArray *array, NSError *error) {
        
        if (error) {
            NSLog(@"%@",error);
        }else if (array){
       
            for (BmobObject * note in array) {
                NoteModel * model = [[NoteModel alloc]init];

                    model.objectId = [note objectForKey:@"objectId"];
                    model.userId = [note objectForKey:@"userId"];
                    model.noteTitle = [note objectForKey:@"noteTitle"];
                    model.noteText = [note objectForKey:@"noteText"];
                    model.noteUrlArr = [note objectForKey:@"noteImage"];
                    model.noteCreatedAt = [AllUtils getDateFromString:[note objectForKey:@"createdAt"]];
                    
                    [self.dataArray addObject:model];
                }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.tableView reloadData];
                
                [SVProgressHUD dismiss];
                
            });
        }

    }];
    
}

#pragma mark - UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (isEditing==NO) {
        
        return self.dataArray.count;
    }
    return self.editArray.count;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NoteCell * cell = [tableView dequeueReusableCellWithIdentifier:@"NoteCell"];
    NoteModel * model =self.dataArray[indexPath.row];
    cell.model = model;
  
    return cell;
}

#pragma mark -UITableViewDelegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NoteModel * model=nil;
    
    if (isEditing==NO) {
         model = [self.dataArray objectAtIndex:indexPath.row];
    }else{
         model = [self.editArray objectAtIndex:indexPath.row];
    }
    
    WriteViewController * writeVC = [[WriteViewController alloc]init];
    
    writeVC.noteTitle = model.noteTitle;
    writeVC.noteText = model.noteText;
    writeVC.noteImage = model.noteUrlArr;
    writeVC.index = 2;
    
    [self.navigationController pushViewController:writeVC animated:YES];

}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
   
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        
      NoteModel * model = self.dataArray[indexPath.row];
        
      [BmobOperation deleteNoteFromDatabase:@"Note" noteId:model.objectId] ;
       
      [self.dataArray removeObjectAtIndex:indexPath.row];
        
      self.editArray = [NSMutableArray arrayWithArray:self.dataArray];
      isEditing = YES;
     [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

    }
 
}

-(void)leftBarButtonItemClick{
    
    [self.sideMenuViewController presentLeftMenuViewController];

}

-(void)rightBarButtonItemClick{
    
    SearchViewController * searchVC = [[SearchViewController alloc]init];
    if (isEditing==NO) {
        searchVC.dataArray = self.dataArray;
    }else{
        searchVC.dataArray = self.editArray;
    }
    [self.navigationController pushViewController:searchVC animated:YES];
}

-(void)middleButtonClick{
    
    WriteViewController * wirte = [[WriteViewController alloc]init];
    wirte.index = 2;
    
    [self.navigationController pushViewController:wirte animated:YES];
    
}

#pragma mark - 可视化视图

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
